//
//  ComposeTypeView.swift
//  VVbo
//
//  Created by Mr.Run on 2017/9/5.
//  Copyright © 2017年 Mr.Run. All rights reserved.
//

import UIKit
import pop

class ComposeTypeView: UIView {

    @IBOutlet weak var returnBtn: UIButton!
    @IBOutlet weak var returnBtnCenterXCons: NSLayoutConstraint!
    @IBOutlet weak var closeBtnCenterXCons: NSLayoutConstraint!
    @IBOutlet weak var scrollView: UIScrollView!
    
    fileprivate var completionBlock:((_ clsName: String?)->())?
    
    fileprivate let buttonsInfo = [["imageName": "tabbar_compose_idea", "title": "文字", "clsName": "ComposeViewController"],
                                   ["imageName": "tabbar_compose_photo", "title": "照片/视频"],
                                   ["imageName": "tabbar_compose_weibo", "title": "长微博"],
                                   ["imageName": "tabbar_compose_lbs", "title": "签到"],
                                   ["imageName": "tabbar_compose_review", "title": "点评"],
                                   ["imageName": "tabbar_compose_more", "title": "更多", "actionName": "clickMore"],
                                   ["imageName": "tabbar_compose_friend", "title": "好友圈"],
                                   ["imageName": "tabbar_compose_wbcamera", "title": "微博相机"],
                                   ["imageName": "tabbar_compose_music", "title": "音乐"],
                                   ["imageName": "tabbar_compose_shooting", "title": "拍摄"]]
    
    @IBAction func returnBtnClick(_ sender: Any) {
        scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
        returnBtn.isHidden = true
        
        closeBtnCenterXCons.constant = 0
        returnBtnCenterXCons.constant = 0
        UIView.animate(withDuration: 0.25, animations: { 
            self.layoutIfNeeded()
            self.returnBtn.alpha = 0
        }) { (_) in
            self.returnBtn.isHidden = true
            self.returnBtn.alpha = 1
        }
    }
    @IBAction func composeBtnClick(_ sender: Any) {
        hideButtons()
//        removeFromSuperview()
    }
    class func composeTypeView()-> ComposeTypeView {
        
        let nib = UINib(nibName: "ComposeTypeView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! ComposeTypeView
        v.frame = UIScreen.main.bounds
        v.setupUI()
        return v
    }
    
    func show(completion:@escaping (_ clsName: String?)->()) {
        completionBlock = completion
        guard let vc = UIApplication.shared.keyWindow?.rootViewController else {
            return
        }
        vc.view.addSubview(self)
        showCurrentView()
    }
    
//    override func awakeFromNib() {
//        super.awakeFromNib()
//        setupUI()
//    }
    
    @objc fileprivate func buttonClick(selectedButton: ComposeTypeButton) {
        print("真的点击了")
        
        
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let v = scrollView.subviews[page]
        
        for (i, btn) in v.subviews.enumerated() {
            let scaleAnim = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
            let scale = (selectedButton == btn) ? 2:0.2
            scaleAnim?.toValue = NSValue(cgPoint: CGPoint(x: scale, y: scale))
            scaleAnim?.duration = 0.5
            btn.pop_add(scaleAnim, forKey: nil)
            
            let alphaAnim:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            alphaAnim.toValue = 0.2
            alphaAnim.duration = 0.5
            btn.pop_add(alphaAnim, forKey: nil)
            
            if i==0 {
                alphaAnim.completionBlock = {(_, _)->() in
                    
                    self.completionBlock?(selectedButton.clsName)
                    
                }
            }
            
        }
        
    }
    
    @objc fileprivate func clickMore() {
        print("更多")
        
        scrollView.setContentOffset(CGPoint(x: scrollView.bounds.width, y: 0), animated: true)
        returnBtn.isHidden = false
        let margin = scrollView.bounds.width/6
        closeBtnCenterXCons.constant += margin
        returnBtnCenterXCons.constant -= margin
        UIView.animate(withDuration: 0.25) { 
            self.layoutIfNeeded()
        }
    }
    
}

fileprivate extension ComposeTypeView {
    
    fileprivate func showCurrentView() {
        let anim = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        anim?.fromValue = 0
        anim?.toValue = 1
        anim?.duration = 0.25
        pop_add(anim, forKey: nil)
        showButtons()
    }
    
    private func showButtons() {
        let v = scrollView.subviews[0]
        
        for (i ,btn) in v.subviews.enumerated() {
            let anim:POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            anim.fromValue = btn.center.y + 350
            anim.toValue = btn.center.y
            anim.springBounciness = 8
            anim.springSpeed = 8
            anim.beginTime = CACurrentMediaTime() + TimeInterval(i) * 0.025
            btn.pop_add(anim, forKey: "btn")
        }
        
    }
    
    fileprivate func hideButtons() {
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let v = scrollView.subviews[page]
        
        for (i ,btn) in v.subviews.enumerated().reversed() {
            let anim:POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            anim.fromValue = btn.center.y
            anim.toValue = btn.center.y + 350
            anim.beginTime = CACurrentMediaTime() + TimeInterval(v.subviews.count-i) * 0.025
            btn.pop_add(anim, forKey: nil)
            if i == 0 {
                anim.completionBlock = {(_, _)->() in
                    self.hideCurrentView()
                }
            }
        }
    }
    
    fileprivate func hideCurrentView() {
        let anim:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        anim.fromValue = 1
        anim.toValue = 0
        anim.duration = 0.25
        pop_add(anim, forKey: nil)
        anim.completionBlock = {(_, _)->() in
            self.removeFromSuperview()
        }
    }
    
}


fileprivate extension ComposeTypeView {
    
    func setupUI() {
        layoutIfNeeded()
        let rect = scrollView.bounds
        
        let width = scrollView.bounds.width
        for i in 0..<2 {
            let v = UIView(frame: rect.offsetBy(dx: CGFloat(i)*width, dy: 0))
            
            addButtons(v: v, idx: i*6)
            scrollView.addSubview(v)
        }
        scrollView.contentSize = CGSize(width: 2*width, height: 0)
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.bounces = false
        scrollView.isScrollEnabled = false
    }
    
    func addButtons(v: UIView, idx: Int) {
        
        let count = 6
        
        for i in idx..<(idx + count) {
            
            if i >= buttonsInfo.count{
                break
            }
            
            let dict = buttonsInfo[i]
            
            guard let imageName = dict["imageName"],
            let title = dict["title"] else {
                continue
            }
            let btn = ComposeTypeButton.composeTypeButton(imageName: imageName, title: title)
            v.addSubview(btn)
            
            if let actionName = dict["actionName"] {
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            }else{
                btn.addTarget(self, action: #selector(buttonClick), for: .touchUpInside)
            }
            btn.clsName = dict["clsName"]
        }
        
        let btnSize = CGSize(width: 70, height: 100)
        let margin = (v.bounds.width - 3*btnSize.width)/4
        for (i, btn) in v.subviews.enumerated() {
            let y: CGFloat = (i>2) ? (v.bounds.height - btnSize.height) : 0
            let col = i % 3
            let x = CGFloat(col + 1)*margin + CGFloat(col)*btnSize.width
            btn.frame = CGRect(x: x, y: y, width: btnSize.width, height: btnSize.height)
        }
    }
    
}
